import 'package:ycbl/model/calendar_task_list_entity.dart';
import 'package:ycbl/net/repository/bl_repository.dart';
import 'package:ycbl/utils/log_util.dart';
import 'package:ycbl/utils/user_config.dart';
import 'package:ycbl/widget/provider/base_view_state_model.dart';

/// 日历任务 view model
class CalendarTaskViewModel extends BaseViewStateModel {

  /// 班课任务是否请求完成
  bool _isNormalTaskPrepared = false;
  /// 一对一任务是否请求完成
  bool _isClassTaskPrepared = false;

  int successTime = 0;

  //临时存储列表
  List<CalendarTaskEntity> _calendarTaskList = [];

  Map<DateTime, List<CalendarTaskEntity>> _calendarTaskMap = {};
  ///按日期分组任务
  Map<DateTime, List<CalendarTaskEntity>> get calendarTaskMap => _calendarTaskMap;

  /// 获取日历任务
  getCalendarTasks(DateTime startDate, DateTime endDate) {

    //setBusy();

    //重置旧数据
    _calendarTaskList.clear();
    _isNormalTaskPrepared = false;
    _isClassTaskPrepared = false;
    int userId = UserConfig().getUserId();

    // 获取一对一任务
    BLRepository.getClassCalendarTasks(
      startDate, endDate, userId, (classTasks){
      _calendarTaskList.addAll(classTasks);
      _isClassTaskPrepared = true;
      _notifyDataPrepared();
    }, (err){
      setError(err);
    },
    );

    // 获取普通班课任务
    BLRepository.getNormalCalendarTasks(
      startDate, endDate, userId, (normalTasks){
      _calendarTaskList.addAll(normalTasks);
      _isNormalTaskPrepared = true;
      _notifyDataPrepared();
    }, (err){
      setError(err);
    },);

  }

  /// 两组数据都获取成功
  _notifyDataPrepared() {
    LogUtil.d('calendar task _notifyDataPrepared ($_isNormalTaskPrepared, $_isClassTaskPrepared)');
    if(!isError && _isNormalTaskPrepared && _isClassTaskPrepared) {

      successTime ++;

      //按日期分组
      _groupTasksByDate();

      setIdle();
    }
  }

  ///按日期分组任务
  _groupTasksByDate() {
    // 清空集合
    _calendarTaskMap.clear();
    if (_calendarTaskList.isEmpty) {
      return;
    }
    //按日期分组 yyyy-MM-dd 00:00:000
    _calendarTaskMap = Map.fromIterable(
        _calendarTaskList,
        key: (key) => key.date,
        value: (value) {
          return _calendarTaskList.where((element) => element.date == value.date).toList();
        }
    );

    //清空列表 释放内存
    _calendarTaskList.clear();

  }

  ///获取某一天的任务
  List<CalendarTaskEntity> getTasksAtDay(DateTime date) {
    DateTime key = DateTime(date.year, date.month, date.day);
    return _calendarTaskMap[key] ?? [];
  }
}